﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace WFtest01
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            ServicePointManager.ServerCertificateValidationCallback = Validator;
            InitializeComponent();
        }

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            buttonLoad.Enabled = false;
            SetStatus("Requesting...");

            var l = GetLifeHtml().split("\n").Where(i => !string.IsNullOrEmpty(i.Trim())).ToList();
            listBoxData.DataSource = l;
            
            buttonLoad.Enabled = true;
            SetStatus("Completed at " + DateTime.Now);
        }

        private string GetLifeHtml()
        {
            const string Code = "025";
            const string Phone = "*";
            const string Password = "*";

            string postData = "Code=" + Code + "&Phone=" + Phone + "&Password=" + Password;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            try
            {
                var r =  PostHtml("https://issa.life.com.by/Account.aspx", byteArray);
                SetStatus("Formating...");
                r = r.StripHtml();
                return r;

            }
            catch (Exception)
            {
                return "Ошибко: Что-то случилось или нет соединения...";
            }
        }

        private static string PostHtml(string url, byte[] byteArray)
        {
            ServicePointManager.ServerCertificateValidationCallback = Validator;
            var request = (HttpWebRequest)WebRequest.Create(url);
            var cookies = new CookieContainer();
            request.CookieContainer = cookies;

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = byteArray.Length;
            using (Stream dataStream = request.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);
            }
            using (WebResponse response = request.GetResponse())
            {
                // Get the stream containing content returned by the server.
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        string responseFromServer = reader.ReadToEnd();
                        // Display the content.
                        return responseFromServer;
                    }
                }
            }
        }

        private static string GetHtml(string url)
        {
            ServicePointManager.ServerCertificateValidationCallback = Validator;
            var request = (HttpWebRequest)WebRequest.Create(url);
            var cookies = new CookieContainer();
            request.CookieContainer = cookies;

            using (WebResponse response = request.GetResponse())
            {
                // Get the stream containing content returned by the server.
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(responseStream))
                    {
                        string responseFromServer = reader.ReadToEnd();
                        // Display the content.
                        return responseFromServer;
                    }
                }
            }
        }

        private void SetStatus(string status)
        {
            lblStatus.Text = status;
            lblStatus.Invalidate();
            lblStatus.Update();
            lblStatus.Refresh();
            Application.DoEvents();
        }

        public static bool Validator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }

    public static class Helper
    {
        public static string[] split(this string s, string separator)
        {
            return s.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries);
        }

        public static string StripHtml(this string htmlCode)
        {
            htmlCode = htmlCode.Replace("\t", " ");
            htmlCode = Regex.Replace(htmlCode, "\\s+", " ");
            htmlCode = Regex.Replace(htmlCode, "<head.*?</head>", string.Empty,
                                                RegexOptions.IgnoreCase | RegexOptions.Singleline);

            htmlCode = Regex.Replace(htmlCode, "<script.*?</script>", string.Empty,
                                     RegexOptions.IgnoreCase | RegexOptions.Singleline);
            var builder = new StringBuilder(htmlCode);

            string[] oldWords = { "&nbsp;", "&amp;", "&quot;", "&lt;", "&gt;", "&reg;", "&copy;", "&bull;", "&trade;" };
            string[] newWords = { " ", "&", "\"", "<", ">", "Â®", "Â©", "â€¢", "â„¢" };
            for (int i = 0; i < oldWords.Length; i++)
                builder.Replace(oldWords[i], newWords[i]);

            return Regex.Replace(builder.ToString(), "<[^>]*>", "\n").Trim();
        }
    }
}